package com.xq.controller.admin.upload;

import com.xq.service.UploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author sgl
 * @Date 2018-05-15 14:04
 */
@RestController
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @Value("${imgpath}")
    public String imgpath;

    @Autowired
    private UploadService uploadService;

    @PostMapping("/admin/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, ServletException {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        // handler调用文件上传的service 得到文件的虚拟路径
        String filepath = uploadService.uploadImg(file);
        return imgpath + filepath;
    }


    @PostMapping("/admin/uploadjson")
    @ResponseBody
    public Map<String, Object> uploadJson(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, ServletException {
        if (file.isEmpty()) {
            return null;
        }
        // handler调用文件上传的service 得到文件的虚拟路径
        String filepath = uploadService.uploadImg(file);
        Map<String, Object> map = new HashMap<>();
        map.put("url", imgpath + filepath);
        return map;
    }

}
